package com.example.springbootpro.notic;

import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

 import java.util.Enumeration;

@Aspect
@Component
@Order(2)
public class RequestLoggingAspect {

    private static final Logger logger = LoggerFactory.getLogger(RequestLoggingAspect.class);

    // 拦截所有Controller层的公共方法
    @Pointcut("execution(* com.example.springbootpro.controller.mysql.*.*(..))")
    public void controllerPointcut() {}

    @Before("controllerPointcut()")
    public void logRequest(JoinPoint joinPoint) {
//        在这个地方需要设置一下
         ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return;
        }
        
        HttpServletRequest request = attributes.getRequest();
        
        // 打印请求基本信息
        logger.info("===================== 请求开始 =====================");
        logger.info("请求URL: {} {}", request.getMethod(), request.getRequestURL());
        logger.info("请求IP: {}", request.getRemoteAddr());
        logger.info("请求类方法: {}.{}", 
            joinPoint.getSignature().getDeclaringTypeName(), 
            joinPoint.getSignature().getName());
        
        // 打印请求参数
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String paramName = parameterNames.nextElement();
            logger.info("请求参数: {} = {}", paramName, request.getParameter(paramName));
        }
        
        // 打印请求头
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            logger.info("请求头: {} = {}", headerName, request.getHeader(headerName));
        }
        
//        Object[] args = joinPoint.getArgs();
//        if (args != null && args.length > 0) {
//            for (int i = 0; i < args.length; i++) {
//                logger.info("方法参数 {}: {} = {}", i, args[i].getClass().getSimpleName(), args[i]);
//            }
//        }
        
        logger.info("===================== 请求结束 =====================");
    }
}